package org.moonlight.jvm.classpath.entry;

import lombok.EqualsAndHashCode;
import org.moonlight.jvm.classpath.Entry;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 以文件分隔符（如 ;）分割的多个路径
 *
 * @author Moonlight
 * @createTime 2023/8/14 15:26
 **/
@EqualsAndHashCode
public class CompositeEntry implements Entry {

    /** 类路径集合 **/
    private final List<Entry> entryList;

    public CompositeEntry(String path) {
        this.entryList = new ArrayList<>();
        String[] split = path.split(File.pathSeparator);
        for (String p : split) {
            this.entryList.add(Entry.create(p));
        }
    }

    @Override
    public byte[] readClass(String className) throws IOException {
        for (Entry e : entryList) {
            try {
                return e.readClass(className);
            } catch (Exception ignore) {

            }
        }
        throw new IOException("class not found " + className);
    }

    @Override
    public String toString() {
        return String.join(
                File.pathSeparator,
                entryList.parallelStream().map(Entry::toString).collect(Collectors.toList()).toArray(new String[]{})
        );
    }
}
